package com.example.lib_base

import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.blankj.utilcode.util.ToastUtils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.receiveAsFlow
import kotlinx.coroutines.launch

abstract class BaseViewModel<uiIntent:UIIntent>:ViewModel() {
    private val _uiIntent = Channel<UIIntent> { Channel.UNLIMITED }
    private val _state = MutableStateFlow<UiState>(UiState.OnLoading)
    val state:StateFlow<UiState>
        get() =_state
    init {
        viewModelScope.launch {
            _uiIntent.receiveAsFlow().collect{
                handleIntent(it)
            }
        }
    }

    abstract fun handleIntent(it: UIIntent)

    fun sendIntent(intent:UIIntent){
        viewModelScope.launch {
            _uiIntent.send(intent)
        }
    }

    fun httpRequest(request:Flow<Res<Any>>,type: StateType = StateType.DEFAULT){
        viewModelScope.launch {
            request.flowOn(Dispatchers.IO)
                .catch {
                    ToastUtils.showLong("网络请求错误:${it.message}")
                    Log.e("TagA","网络请求错误:${it.message}")
                }.collect{
                    if (it.code == 0){
                        _state.value = UiState.OnSuccess(it.data)
                    }else{
                        _state.value=UiState.OnError(it.msg)
                    }
                }
        }
    }
}